package com.hut.oa.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.transaction.Transactional;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.hut.oa.model.bean.Directory;
import com.hut.oa.model.bean.FileManage;
import com.hut.oa.model.bean.User;
import com.hut.oa.model.dao.file.DirectoryDao;
import com.hut.oa.model.dao.file.FileManageDao;


@Service
@Transactional
public class FileService {

	@Autowired
	FileManageDao filedao;
	
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private FileManageDao dao;

	@Autowired
	private DirectoryDao dirdao;
	@Value(value = "${file.upload.path}")
	private String rootpath;

	// 新建文件夹
	public void newfolder(String path, String fatherid, String name, User u) {

		String finnalpath = null;
		if (path.equals("undefined")) {
			finnalpath = "upload/" + u.getId() + "/" + name + "";
		} else {
			finnalpath = "" + path + "/" + name + "";
		}
		File file = new File(this.rootpath, finnalpath);
		file.mkdirs();
		Directory dir = new Directory();
		Directory dir2 = new Directory();

		dir2.setId(Long.parseLong(fatherid));
		dir.setPath(finnalpath);
		dir.setPid(dir2);
		dir.setText(name);
		dir.setUser(u);
		dirdao.save(dir);
		logger.info(file.getAbsolutePath());
	}

	public String uploadefile(MultipartFile f, String path) throws IllegalStateException, IOException {
		File file = new File(this.rootpath, path);

		logger.info(file.getAbsolutePath());

		if (!file.exists()) {
			file.mkdirs();
		}
		// 获取文件后缀
		String suffix = FilenameUtils.getExtension(f.getOriginalFilename());
		// 赋予文件新名字
		String newname = UUID.randomUUID().toString().toLowerCase() + "." + suffix;
		// 文件上传路径
		File savepath = new File(file, newname);
		// 上传文件
		f.transferTo(savepath);
		return savepath.getAbsolutePath().replace(rootpath, "");
	}

	// 上传保存文件
	public void save(MultipartFile f, String path, Directory dir, User u) throws IllegalStateException, IOException {
		File file = new File(this.rootpath, path);
		if (!file.exists()) {
			file.mkdirs();
		}
		
		// 获取文件后缀
		String suffix = FilenameUtils.getExtension(f.getOriginalFilename());
		// 赋予文件新名字
		String newname = UUID.randomUUID().toString().toLowerCase() + "." + suffix;
		// 文件上传路径
		File savepath = new File(file, newname);
		// 上传文件
		f.transferTo(savepath);
		FileManage upload = new FileManage();
		// 目录id
		upload.setDir(dir);
		// 文件名字
		upload.setFilename(f.getOriginalFilename());
		// 文件后缀
		upload.setSuffix(suffix);
		// 保存更新时间
		upload.setUpdateTime(new Date());
		// 保存图标路径
		upload.setPath(savepath.getAbsolutePath().replace(rootpath, ""));
		// 文件大小
		upload.setSize(f.getSize());
		// 文件类型
		upload.setFiletype(f.getContentType());
		// 保存用户
		upload.setUser(u);
		// 保存至数据库
		dao.save(upload);
	}

	// 移动文件
	public void deletefile(Long fileid, String id, String directpath) throws IOException {
		copy(fileid, id, directpath);
		FileManage f = dao.findById(fileid);
		File ff = new File(this.rootpath + File.separator + f.getPath());
		if (ff.isFile()) {
			ff.delete();
		}
	}

	// 复制文件
	public void copy(Long fileid, String id, String directpath) throws IOException {

		FileManage oldfile = dao.findById(fileid);

		File file = new File(this.rootpath, oldfile.getPath());

		File filemkdir = new File(this.rootpath, directpath);

		FileInputStream ins = new FileInputStream(file);

		String newname = UUID.randomUUID().toString().toLowerCase() + "." + oldfile.getSuffix();

		if (!filemkdir.exists()) {
			filemkdir.mkdirs();
		}
		String newpath = directpath + "\\" + newname;
		String dire = this.rootpath + "\\" + newpath;
		FileOutputStream out = new FileOutputStream(dire);
		byte[] b = new byte[1024];
		int n = 0;
		while ((n = ins.read(b)) != -1) {
			out.write(b, 0, n);
		}
		ins.close();
		out.close();
		Directory dirid = new Directory();
		dirid.setId(Long.parseLong(id));
		FileManage newfile = new FileManage();
		newfile.setDir(dirid);
		newfile.setFilename(oldfile.getFilename());
		newfile.setSuffix(oldfile.getSuffix());
		newfile.setUpdateTime(new Date());
		newfile.setPath(newpath);
		newfile.setSize(oldfile.getSize());
		dao.save(newfile);
	}

	// 复制文件夹
	public Map<String, String> copyfolder(Directory dir, String direct, String id) {
		int index = dir.getPath().lastIndexOf("/");

		String path = direct + "/" + dir.getPath().substring(index + 1, dir.getPath().length());

		File file = new File(this.rootpath, path);
		if (!file.exists()) {
			file.mkdirs();
		}
		Directory dirid = new Directory();
		dirid.setId(Long.parseLong(id));

		Directory newdir = new Directory();
		newdir.setText(dir.getText());
		newdir.setPath(path);
		newdir.setPid(dirid);
		dirdao.save(newdir);
		Map<String, String> map = new HashMap<>();
		map.put("id", newdir.getId().toString());
		map.put("path", newdir.getPath());
		return map;
	}

	// 删除本地文件夹
	public void deletefolder(File file) {
		if (file.isDirectory()) {
			String[] children = file.list();
			for (int i = 0; i < children.length; i++) {
				deletefolder(new File(file, children[i]));
			}
		}
		file.delete();
	}
	
	
	
	//重命名
	public void newname(String name,Long id){
		filedao.updatenamebyid(name, id);
	}
	
	public int updateid(Long id,Directory dir,Integer type){
		return	filedao.updateisdelete(id,type,dir);
	}
	
	/**
	 * 生成文件夹的树
	 */
	public List<Directory> tree(User u){	
		List<Directory> directory=dirdao.findByPidIsNullAndUserAndIsDelete(u,0);
		this.sontree(directory);
		logger.info(directory+"");
		return directory;
	}
	
	public void sontree(List<Directory> directory){		
		for (Directory directory2 : directory) {
			Map<String, String> map=new HashMap<>();
			List<Directory> dirson=dirdao.findByPidAndIsDelete(directory2,0);	
			directory2.setChildren(dirson);	
			if(dirson.size()>0){
				this.sontree(dirson);		
			}								
		}	
	}	
}
